package com.bysj.money_diary;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.Fragment;
import android.app.TimePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.app.TimePickerDialog.OnTimeSetListener;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.util.Log;
import android.view.ContextThemeWrapper;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.view.animation.AnimationUtils;
import android.widget.ArrayAdapter;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;

@SuppressLint({ "HandlerLeak", "NewApi" })
public class Jiyibi extends Fragment implements OnClickListener{
	private View view;
	private TextView leibie, date, time, beizhu;
	private EditText jine;
	private FrameLayout zhichu_fl, shouru_fl, jiedai_fl, save_fl, cancel_fl, del_fl;
	private LinearLayout pic_ll;
	//
	private ImageView zhichu_iv, shouru_iv, jiedai_iv, pic;
    public static MessageHandler mh;//TODO?
    public static final int leibie_msg = 1010, beizhu_msg = 1020;
    public static final int zhichu_flag = 2010, shouru_flag = 2020, jiedai_flag = 2030;
    private int now_flag = zhichu_flag;
    Data dataHelper; //数据库
    private int update_type, update_id, update_flag;
    private boolean isUpdate = false;//
    private TextView zhichu_text, shouru_text, jiedai_text;

    private String picpath = "";//照片路径
    private static final int PHOTO_WITH_CAMERA = 1010;//拍摄照片
    private static final int PHOTO_WITH_DATA = 1020;//从SD卡获得照片
    private File PHOTO_DIR;
    private File capturefile;//拍摄的照片文件
    
    Zhichu zc = new Zhichu();
    Shouru sr = new Shouru();
	private String tag;
	
	/*权限问题*/
    private static final int REQUEST_EXTERNAL_STORAGE = 1;  
    private static String[] PERMISSIONS_STORAGE = {  
            Manifest.permission.ACCESS_COARSE_LOCATION,  
            Manifest.permission.ACCESS_FINE_LOCATION,  
            Manifest.permission.ACCESS_WIFI_STATE,  
            Manifest.permission.ACCESS_NETWORK_STATE,  
            Manifest.permission.CHANGE_WIFI_STATE,  
            Manifest.permission.READ_PHONE_STATE,  
            Manifest.permission.WRITE_EXTERNAL_STORAGE,  
            Manifest.permission.INTERNET,  
            Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS}; 
    
    public static void verifyStoragePermissions(Activity activity) {  
        // Check if we have write permission  
        int permission = ActivityCompat.checkSelfPermission(activity,  
                Manifest.permission.ACCESS_FINE_LOCATION);  
      
        if (permission != PackageManager.PERMISSION_GRANTED) {  
            // We don't have permission so prompt the user  
            ActivityCompat.requestPermissions(activity, PERMISSIONS_STORAGE,  
                    REQUEST_EXTERNAL_STORAGE);  
        }  
    }  
	
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		view = inflater.inflate(R.layout.activity_jiyibi, container, false);
		mh = new MessageHandler();
		initZhiChu();
		initUpdate();
		
		return view;
	}
	
	/*
	 * initZhiChu();
	 */
	private void initZhiChu() {
		//金额
        jine = (EditText) view.findViewById(R.id.jiyibi_jine_text);
        jine.setOnClickListener(new TextClick());
        // 类别
        leibie = (TextView) view.findViewById(R.id.jiyibi_leibie_text);
        leibie.setOnClickListener(new TextClick());
        // 日期
        date = (TextView) view.findViewById(R.id.jiyibi_date_text);
        date.setText(GetTime.getYear() + "-" + GetTime.getMonth() + "-" + GetTime.getDay());
        date.setOnClickListener(new TextClick());
        // 时间
        time = (TextView) view.findViewById(R.id.jiyibi_time_text);
        time.setText(GetTime.getHour() + ":" + GetTime.getMinute());
        time.setOnClickListener(new TextClick());
        // ע备注
        beizhu = (TextView) view.findViewById(R.id.jiyibi_beizhu_text);
        beizhu.setOnClickListener(new TextClick());
        // 支出图片
        pic = (ImageView) view.findViewById(R.id.jiyibi_zhichu_addpic_iv);
        pic.setOnClickListener(new TextClick());
        
        pic_ll = (LinearLayout) view.findViewById(R.id.jiyibi_pic_ll);

        zhichu_iv = (ImageView) view.findViewById(R.id.jiyibi_zhichu_iv);
        shouru_iv = (ImageView) view.findViewById(R.id.jiyibi_shouru_iv);
        jiedai_iv = (ImageView) view.findViewById(R.id.jiyibi_jiedai_iv);

        zhichu_fl = (FrameLayout) view.findViewById(R.id.jiyibi_zhichu_fl);
        zhichu_fl.setOnClickListener(this);
        shouru_fl = (FrameLayout) view.findViewById(R.id.jiyibi_shouru_fl);
        shouru_fl.setOnClickListener(this);
        jiedai_fl = (FrameLayout) view.findViewById(R.id.jiyibi_jiedai_fl);
        jiedai_fl.setOnClickListener(this);
        save_fl = (FrameLayout) view.findViewById(R.id.jiyibi_save_fl);
        save_fl.setOnClickListener(this);
        cancel_fl = (FrameLayout) view.findViewById(R.id.jiyibi_cancel_fl);
        cancel_fl.setOnClickListener(this);
        del_fl = (FrameLayout) view.findViewById(R.id.jiyibi_del_fl);
        del_fl.setOnClickListener(this);
        del_fl.setVisibility(View.INVISIBLE);
        del_fl.setVisibility(View.INVISIBLE);
    }
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
        case R.id.jiyibi_zhichu_fl://支出
            setTopBG(zhichu_flag, zhichu_iv);
            leibie.setText("餐饮>早餐");
            break;
        case R.id.jiyibi_shouru_fl://收入
            setTopBG(shouru_flag, shouru_iv);
            leibie.setText("工资");
            break;
        case R.id.jiyibi_jiedai_fl://借贷
            setTopBG(jiedai_flag, jiedai_iv);
            leibie.setText("借入");
            break;
        case R.id.jiyibi_save_fl://保存
            saveToDB();
            break;
        case R.id.jiyibi_cancel_fl://重新加载
        	this.getActivity().finish();
            Intent intent = new Intent(this.getActivity(),MainActivity.class);  
            startActivity(intent); 
            break;
        case R.id.jiyibi_del_fl://删除
            dataHelper = new Data(this.getActivity());
            switch (update_flag) {
            case zhichu_flag:
                int i1 = dataHelper.DelZhiChuInfo(update_id);
                if (i1 > 0) {
                    showMsg("删除...");
                    this.getActivity().finish();
                } else {
                    showMsg("已经删除！");
                }
                break;
            case shouru_flag:
                int i2 = dataHelper.DelShouRuInfo(update_id);
                if (i2 > 0) {
                    showMsg("删除成功！");
                    this.getActivity().finish();
                    Intent intent1 = new Intent(this.getActivity(),MainActivity.class);  
                    startActivity(intent1); 
                } else {
                    showMsg("已经删除，请重新查询...");
                }
                break;
            }
            break;
        }
	}
	
	/*
	 * initUpdate()
	 */
	private void initUpdate() {
		Intent intent = this.getActivity().getIntent();//获取原始数据
		if (intent.hasExtra("update")) {
            zhichu_text = (TextView) view.findViewById(R.id.jiyibi_zhichu_text);
            shouru_text = (TextView) view.findViewById(R.id.jiyibi_shouru_text);
            jiedai_text = (TextView) view.findViewById(R.id.jiyibi_jiedai_text);
            del_fl.setVisibility(View.VISIBLE);
            isUpdate = true;
            update_type = intent.getIntExtra("type", 0);
            update_id = intent.getIntExtra("id", 0);
            ArrayList<?> mingXiList = ChazhangbenAdapter.mingXiList;
            if (update_type == zhichu_flag) {
                for (Object zhichu : mingXiList) {
                    Zhichu zc = (Zhichu) zhichu;
                    if (update_id == zc.getZc_Id()) {
                        this.zc = zc;
                        getZhiChuType(zc);//TODO
                        return;
                    }
                }
            } else if (update_type == shouru_flag) {
                for (Object shouru : mingXiList) {
                    Shouru sr = (Shouru) shouru;
                    if (update_id == sr.getSr_Id()) {
                        this.sr = sr;
                        getShouRuType(sr);
                        return;
                    }
                }
            }
        }
	}
	/*
	 * getZhiChuType(Zhichu zc2)
	 */
	private void getZhiChuType(Zhichu zc2) {
		pic_ll.setVisibility(View.GONE);
        if (zc.getZc_Item().equals(Item.jiechu) || zc.getZc_Item().equals(Item.huankuan)) {
            now_flag = jiedai_flag;
            jiedai_text.setText("借贷编辑");
            leibie.setText(zc.getZc_Item());
            setTopBG(now_flag, jiedai_iv);
            zhichu_fl.setVisibility(View.INVISIBLE);
            shouru_fl.setVisibility(View.INVISIBLE);
        } else {
            now_flag = zhichu_flag;
            zhichu_text.setText("支出编辑");
            leibie.setText(zc.getZc_Item() + ">" + zc.getZc_SubItem());
            setTopBG(now_flag, zhichu_iv);
            jiedai_fl.setVisibility(View.INVISIBLE);
            shouru_fl.setVisibility(View.INVISIBLE);
            picpath = zc.getZc_Pic();
            //TODO....
            if (picpath != null && picpath.endsWith("jpg")) {
                File filePic = new File(picpath);//使用指定路径构造一个新文件
                pic.setImageBitmap(decodeFile(filePic));//设置一个位图作为decodeFile(filePic)的内容
            }
        }
        update_flag = zhichu_flag;
        jine.setText(zc.getZc_Count() + "");
        date.setText(zc.getZc_Year() + "-" + zc.getZc_Month() + "-" + zc.getZc_Day());
        time.setText(zc.getZc_Time());
        beizhu.setText(zc.getZc_Beizhu());
	}
	/*
	 * getShouRuType(Shouru sr2)
	 */
	private void getShouRuType(Shouru sr2) {
		pic_ll.setVisibility(View.GONE);
        if (sr.getSr_Item().equals(Item.jieru) || sr.getSr_Item().equals(Item.shoukuan)) {
            now_flag = jiedai_flag;
            jiedai_text.setText("借贷编辑");
            setTopBG(now_flag, jiedai_iv);
            zhichu_fl.setVisibility(View.INVISIBLE);
            shouru_fl.setVisibility(View.INVISIBLE);
        } else {
            now_flag = shouru_flag;
            shouru_text.setText("收入编辑");
            setTopBG(now_flag, shouru_iv);
            jiedai_fl.setVisibility(View.INVISIBLE);
            zhichu_fl.setVisibility(View.INVISIBLE);
        }
        update_flag = shouru_flag;
        jine.setText(sr.getSr_Count() + "");
        leibie.setText(sr.getSr_Item());
        date.setText(sr.getSr_Year() + "-" + sr.getSr_Month() + "-" + sr.getSr_Day());
        time.setText(sr.getSr_Time());
        beizhu.setText(sr.getSr_Beizhu());
	}
	/*
	 * 页面嵌套小背景：支出、收入、借贷
	 */
	private void setTopBG(int now_flag, ImageView iv) {
		this.now_flag = now_flag;
        if (now_flag == zhichu_flag) {
            if (!pic_ll.isShown()) {
                pic_ll.setVisibility(View.VISIBLE);
                pic_ll.setAnimation(AnimationUtils.loadAnimation(this.getActivity(), R.anim.push_left_in));
            }
        } else if (now_flag == shouru_flag) {
            if (pic_ll.isShown()) {
                DongHuaYanChi.dongHuaEnd(pic_ll, this.getActivity(), mh, R.anim.push_left_out, 400);
            }
        } else if (now_flag == jiedai_flag) {
            if (pic_ll.isShown()) {
                DongHuaYanChi.dongHuaEnd(pic_ll, this.getActivity(), mh, R.anim.push_left_out, 400);
            }
        }
        shouru_iv.setImageDrawable(null);
        zhichu_iv.setImageDrawable(null);
        jiedai_iv.setImageDrawable(null);
        iv.setImageResource(R.drawable.jiyibi_tab1_bt_bgs);
        iv.setAnimation(AnimationUtils.loadAnimation(this.getActivity(), R.anim.top_right2left));
	}
	
	/*
	 * 对获得的位图进行处理，使其能够刚好放在“添加图片”处
	 */
	private Bitmap decodeFile(File f) {
		Log.i(tag, "f = " + f);
		Log.i(tag, "f.getAbsolutePath() = " + f.getAbsolutePath());
		Bitmap b = null;
        try {
        	
            Bitmap bb = BitmapFactory.decodeFile(f.getAbsolutePath());//返回抽象路径名的绝对路径名字符串
            Log.i(tag, "f.getAbsolutePath() = " + f.getAbsolutePath());
            Log.i(tag, "bb = " + bb);
            //从文件中解码生成一个位图。如果支付的文件名为空，或者不能解码出一个位图，方法将返回空
            int width = bb.getWidth();
            int height = bb.getHeight();
            if (width > 100 || height > 100) {
                double bi = ((double) height / (double) width);
                b = Bitmap.createScaledBitmap(bb, 100, (int) (bi * 100), true);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return b;
	}
	
	
	
	@Override  
	public void setUserVisibleHint(boolean isVisibleToUser) {  
		super.setUserVisibleHint(isVisibleToUser);  
	  	if (isVisibleToUser) {  
	  		//相当于Fragment的onResume  
	  		this.getActivity().overridePendingTransition(R.anim.zoom_enter, R.anim.zoom_exit);
	        super.onResume();
	 	} else {  
	 		//相当于Fragment的onPause  
	 	}  
	}
	/*
	 * 时间
	 */
	protected Dialog onCreateDialog(int id) {
        if (id == R.id.jiyibi_date_text) {
            Calendar c = Calendar.getInstance();
            OnDateSetListener osl = new OnDateSetListener() {
                @Override
                public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                    date.setText(year + "-" + (monthOfYear + 1) + "-" + dayOfMonth + " ");
                }
            };
            new DatePickerDialog(this.getActivity(), 0, osl, c.get(Calendar.YEAR), c.get(Calendar.MONTH), c.get(Calendar.DAY_OF_MONTH)).show();
        } else if (id == R.id.jiyibi_time_text) {
            Calendar c = Calendar.getInstance();
            OnTimeSetListener otl = new OnTimeSetListener() {
                @Override
                public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
                    time.setText(hourOfDay + ":" + minute);
                }
            };
            new TimePickerDialog(this.getActivity(), 0, otl, c.get(Calendar.HOUR_OF_DAY), c.get(Calendar.MINUTE), true).show();
        }
        return null;
    }
	/*
	 * 提示对话
	 */
	private void showMsg(String string) {
		Toast.makeText(this.getActivity(), string, Toast.LENGTH_SHORT).show();
	}
	/*
	 * 保存到数据库
	 */
	private void saveToDB() {
		dataHelper = new Data(this.getActivity());
        Zhichu zhichu = new Zhichu();
        Shouru shouru = new Shouru();
        //类别
        String leibies = leibie.getText().toString().trim();
        String items[] = leibies.split(">");
        //日期
        String dateString = date.getText().toString().trim();
        String dates[] = dateString.split("-");
        //时间
        String timeString = time.getText().toString().trim();
        //金额
        String jineString = jine.getText().toString().trim();
        //ע备注
        String beizhuString = beizhu.getText().toString().trim();
        if (jineString.equals("")||Double.parseDouble(jineString)==0) {
            showMsg("请输入金额...");
            return;
        }
        if (now_flag == zhichu_flag) {
            zhichu.setZc_Item(items[0]);
            zhichu.setZc_SubItem(items[1]);
            zhichu.setZc_Year(Integer.parseInt(dates[0]));
            zhichu.setZc_Month(Integer.parseInt(dates[1]));
            zhichu.setZc_Day(Integer.parseInt(dates[2]));
            zhichu.setZc_Time(timeString);
            zhichu.setZc_Week(GetTime.getTheWeekOfYear(Integer.parseInt(dates[0]), Integer.parseInt(dates[1]), Integer.parseInt(dates[2])));
            zhichu.setZc_Pic(picpath);
            zhichu.setZc_Count(Double.parseDouble(jineString));
            zhichu.setZc_Beizhu(beizhuString);
            if (!isUpdate) {
                dataHelper.SaveZhiChuInfo(zhichu);
                showMsg("插入成功！");
                picpath = "";
            } else {
                dataHelper.UpdateZhiChuInfo(zhichu, zc.getZc_Id());
                showMsg("更新成功！");
            }
        } else if (now_flag == shouru_flag) {
            shouru.setSr_Item(leibies);
            shouru.setSr_Year(Integer.parseInt(dates[0]));
            shouru.setSr_Month(Integer.parseInt(dates[1]));
            shouru.setSr_Day(Integer.parseInt(dates[2]));
            shouru.setSr_Time(timeString);
            shouru.setSr_Week(GetTime.getTheWeekOfYear(Integer.parseInt(dates[0]), Integer.parseInt(dates[1]), Integer.parseInt(dates[2])));
            shouru.setSr_Count(Double.parseDouble(jineString));
            shouru.setSr_Beizhu(beizhuString);
            if (!isUpdate) {
                dataHelper.SaveShouRuInfo(shouru);
                showMsg("插入成功！");
            } else {
                dataHelper.UpdateShouRuInfo(shouru, sr.getSr_Id());
                showMsg("更新成功！");
            }
        } else if (now_flag == jiedai_flag) {
            if (leibies.equals(Item.jiechu) || leibies.equals(Item.huankuan)) {
                zhichu.setZc_Item(leibies);
                zhichu.setZc_SubItem("");
                zhichu.setZc_Year(Integer.parseInt(dates[0]));
                zhichu.setZc_Month(Integer.parseInt(dates[1]));
                zhichu.setZc_Day(Integer.parseInt(dates[2]));
                zhichu.setZc_Time(timeString);
                zhichu.setZc_Week(GetTime.getTheWeekOfYear(Integer.parseInt(dates[0]), Integer.parseInt(dates[1]), Integer.parseInt(dates[2])));
                zhichu.setZc_Pic("");
                zhichu.setZc_Count(Double.parseDouble(jineString));
                zhichu.setZc_Beizhu(beizhuString);
                if (!isUpdate) {
                    dataHelper.SaveZhiChuInfo(zhichu);
                    showMsg("插入成功！");
                } else {
                    dataHelper.UpdateZhiChuInfo(zhichu, zc.getZc_Id());
                    showMsg("更新成功！");
                }
            } else if (leibies.equals(Item.jieru) || leibies.equals(Item.shoukuan)) {
                shouru.setSr_Item(leibies);
                shouru.setSr_Year(Integer.parseInt(dates[0]));
                shouru.setSr_Month(Integer.parseInt(dates[1]));
                shouru.setSr_Day(Integer.parseInt(dates[2]));
                shouru.setSr_Time(timeString);
                shouru.setSr_Week(GetTime.getTheWeekOfYear(Integer.parseInt(dates[0]), Integer.parseInt(dates[1]), Integer.parseInt(dates[2])));
                shouru.setSr_Count(Double.parseDouble(jineString));
                shouru.setSr_Beizhu(beizhuString);
                if (!isUpdate) {
                    dataHelper.SaveShouRuInfo(shouru);
                    showMsg("插入成功！");
                } else {
                    dataHelper.UpdateShouRuInfo(shouru, sr.getSr_Id());
                    showMsg("更新成功！");
                }
            }
        }
        this.getActivity().finish();
        Intent intent1 = new Intent(this.getActivity(),MainActivity.class);  
        startActivity(intent1); 
        
	}
	
	/*
	 * 内部类继承监听器接口
	 */
	private class TextClick implements OnClickListener {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
            case R.id.jiyibi_jine_text:
                //TODO写个计算器
                break;
            case R.id.jiyibi_leibie_text:
                new Leibie(Jiyibi.this.getActivity(), now_flag);
                break;
            case R.id.jiyibi_date_text:
                onCreateDialog(R.id.jiyibi_date_text);
                break;
            case R.id.jiyibi_time_text:
                onCreateDialog(R.id.jiyibi_time_text);
                break;
            case R.id.jiyibi_beizhu_text://ע
                String beizhuString = beizhu.getText().toString();
                if(beizhuString.equals("")){
                    new Beizhu(Jiyibi.this.getActivity(),"添加备注");
                }else{
                    new Beizhu(Jiyibi.this.getActivity(),beizhuString);  
                }
                break;
            case R.id.jiyibi_zhichu_addpic_iv:
                if (picpath != null && picpath.endsWith("jpg")) {
                    Intent intent = new Intent(Intent.ACTION_VIEW);//用来显示数据
                    Uri uri = Uri.parse("file://" + picpath);
//                    Log.i(tag, "1111111intent =" + intent);
//                    Log.i(tag, "1111111uri =" + uri);
                    intent.setDataAndType(uri, "image/*");
                    startActivity(intent);
                } else {
//                	Log.i(tag, "1111111picpath=" + picpath);
                    choosePic(Jiyibi.this.getActivity());
                }
                break;
            }
        }

		private void choosePic(Context context) {
			final Context dialogContext = new ContextThemeWrapper(context, android.R.style.Theme_Light);
			Log.i(tag, "dialogContext=" + dialogContext);
			PHOTO_DIR = new File(SDrw.SDPATH+ "jizhang/imgcache/");
			Log.i(tag, "SDrw.SDPATH=" + SDrw.SDPATH);
			Log.i(tag, "PHOTO_DIR=" + PHOTO_DIR);
	        if (!PHOTO_DIR.exists()) {
	            PHOTO_DIR.mkdirs();
	        }
	        // 
	        File noMideaFile = new File(PHOTO_DIR, ".nomedia");
	        Log.i(tag, "noMideaFile=" + noMideaFile);
	        if (!noMideaFile.exists()) {
	            try {
	            	//
	                noMideaFile.createNewFile();
	            } catch (IOException e) {
	                e.printStackTrace();
	            }
	        }
	        String[] choices;
	        choices = new String[2];
	        choices[0] = "用相机拍摄"; // 
	        choices[1] = "从相册选择"; // 
	        final ListAdapter adapter = new ArrayAdapter<String>(dialogContext, android.R.layout.simple_list_item_1, choices);
	        final AlertDialog.Builder builder = new AlertDialog.Builder(dialogContext);
	        builder.setTitle("选择照片");
	        builder.setSingleChoiceItems(adapter, -1, new DialogInterface.OnClickListener() {
	            public void onClick(DialogInterface dialog, int which) {
	                dialog.dismiss();
	                switch (which) {
	                case 0: {
	                    String status = Environment.getExternalStorageState();
	                    if (status.equals(Environment.MEDIA_MOUNTED)) {// 
	                        Intent i = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
	                        capturefile = new File(PHOTO_DIR, getPhotoFileName());
	                        try {
	                            capturefile.createNewFile();
	                            i.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(capturefile));// 
	                        } catch (IOException e) {
	                            e.printStackTrace();
	                        }
	                        startActivityForResult(i, PHOTO_WITH_CAMERA);//
	                    } else {
	                        showMsg("调用相机失败");
	                    }
	                    break;
	                }
	                case 1:// 
	                    Intent intent = new Intent();
	                    
	                    intent.setType("image/*");
	                    Log.i(tag, "intent=" + intent);
	                    intent.setAction(Intent.ACTION_GET_CONTENT);
	                    Log.i(tag, "intent=" + intent);
	                    startActivityForResult(intent, PHOTO_WITH_DATA);
	                    break;
	                }
	            }
	        });
	        builder.create().show();
		}
    }
	
	@SuppressLint("SimpleDateFormat")
	public String getPhotoFileName() {
        Date date = new Date(System.currentTimeMillis());
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
        return dateFormat.format(date) + ".jpg";
    }
	
	/*
     * 
     */
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        File file = null;
        Bitmap picb = null;
        ChangePic cp = new ChangePic();
        Log.i(tag, "cp = " + cp);
        if (resultCode == Activity.RESULT_OK) {
            switch (requestCode) {
            case PHOTO_WITH_CAMERA://
                picpath = capturefile.getAbsolutePath();
                System.out.println(picpath);
                file = new File(picpath);
                picb = decodeFile(file);
                pic.setImageBitmap(picb);
                System.out.println("++++++阿拉+++++");
                break;

            case PHOTO_WITH_DATA://
                Uri uri = data.getData();
                String scheme = uri.getScheme();
                Log.i(tag, "uri = " + uri);
                Log.i(tag, "scheme = " + scheme);
                
                if (scheme.equalsIgnoreCase("file")) {//将给定字符串与此字符串进行比较，忽略大小写
                    picpath = uri.getPath();
                    System.out.println(picpath);
                    
                    file = new File(picpath);
                    
                    picb = decodeFile(file);
                    pic.setImageBitmap(picb);
                } else if (scheme.equalsIgnoreCase("content")) {//TODO
                	/*
                	 * getContentResolver()
                	 * 外界的程序通过ContentResolver接口可以访问ContentProvider提供的数据，
                	 * 在Activity当中通过getContentResolver()可以得到当前应用的
                	 * ContentResolver实例
                	 * */
                    Cursor cursor = this.getActivity().getContentResolver().query(uri, null, null, null, null);
                    cursor.moveToFirst();
                    Log.i(tag, "cursor = " + cursor);
                    picpath = cursor.getString(1);
                    Log.i(tag, "picpath = " + picpath);
                    file = new File(picpath);
                    Log.i(tag, "file = " + file);
                    picb = decodeFile(file);
                    Log.i(tag, "picb = " + picb);
                    pic.setImageBitmap(picb);
                }
                break;
            }
          //TODO
            String savePath = SDrw.SDPATH+"jizhang/imgcache/";
            picpath = cp.changPic(picpath, savePath);
        }
        super.onActivityResult(requestCode, resultCode, data);
    }
	
    public class MessageHandler extends Handler {
        public void handleMessage(Message msg) {
            switch (msg.what) {
            case leibie_msg:
                leibie.setText((String) msg.obj);
                break;
            case beizhu_msg:
                beizhu.setText((String) msg.obj);
                break;
            default:
                break;
            }
        }
    }
}
